import { defineStore } from 'pinia'
import api from '@/utils/api'
import { useSocketStore } from './socket'

// 学生状态管理store
export const useStudentsStore = defineStore('students', {
  state: () => ({
    // 学生列表数据
    students: [],
    // 班级学生数据（按班级分组）
    classesList: [],
    // 班级列表（别名）
    classes: [],
    // 班级考勤统计数据
    classesAttendance: [],
    // 班级学生列表
    classStudents: [],
    // 班级考勤详情
    classAttendanceDetail: {},
    // 当前选中的日期
    selectedDate: new Date().toISOString().split('T')[0],
    // 加载状态
    loading: false,
    // 错误信息
    error: null,
    // 实时更新定时器
    updateTimer: null,
    // 更新间隔（毫秒）
    updateInterval: 30000, // 30秒
    // 异常学生列表
    abnormalStudents: [],
    // 统计数据
    statistics: {
      totalStudents: 0,
      arrivedStudents: 0,
      departedStudents: 0,
      overdueArrivals: 0
    },
    // 管理员功能相关状态
    drivers: [],
    selectedClass: null,
    pagination: {
      page: 1,
      itemsPerPage: 10,
      total: 0
    },
    searchQuery: '',
    // 考勤相关
    attendanceStats: {},
    attendanceSettings: {},
    totalCount: 0,
    // 校车相关
    busStudents: [],
    busList: [],
    // 离校相关
    departureStudents: [],
    // 当前学生
    currentStudent: {}
  }),

  getters: {
    // 获取指定班级的学生
    getStudentsByClass: (state) => (classId) => {
      return state.students.filter(student => student.class_id === classId)
    },
    
    // 获取超过入园时间未到的学生
    getOverdueArrivals: (state) => {
      const now = new Date()
      const thresholdTime = new Date()
      thresholdTime.setHours(8, 30, 0, 0) // 8:30为入园时间阈值
      
      // 只在当前时间超过阈值时间后才返回异常学生
      if (now < thresholdTime) {
        return []
      }
      
      return state.students.filter(student => 
        student.arrival_status !== 'arrived' && 
        student.arrival_status !== 'leave' // 排除请假学生
      )
    },
    
    // 获取班级出勤率
    getClassAttendanceRate: (state) => (classId) => {
      const classStudents = state.students.filter(s => s.class_id === classId)
      if (classStudents.length === 0) return 0
      const arrivedCount = classStudents.filter(s => s.arrival_status === 'arrived').length
      return Math.round((arrivedCount / classStudents.length) * 100)
    },
    
    // 获取所有班级出勤统计
    getAllClassesAttendance: (state) => {
      return state.classesAttendance
    },
    
    // 获取总项目数
    totalItems: (state) => {
      return state.pagination.total
    }
  },

  actions: {
    // 初始化WebSocket监听
    initSocketListeners() {
      const socketStore = useSocketStore()
      
      // 监听学生状态更新
      socketStore.on('student-status-updated', (data) => {
        this.handleStudentStatusUpdate(data)
      })
      
      // 监听考勤记录更新
      socketStore.on('attendance-updated', (data) => {
        this.handleAttendanceUpdate(data)
      })
      
      // 监听学生考勤数据响应
      socketStore.on('students-attendance-data', this.handleStudentsAttendanceData)
      
      // 监听班级列表响应
      socketStore.on('classes-data', this.handleClassesData)
      
      // 监听学生列表响应（管理员）
      socketStore.on('students-admin-data', this.handleStudentsAdminData)
      
      // 监听班级学生列表响应
      socketStore.on('class-students-data', this.handleClassStudentsData)
      
      // 监听考勤设置响应
      socketStore.on('attendance-settings-data', this.handleAttendanceSettingsData)
      
      // 监听校车学生列表响应
      socketStore.on('bus-students-data', this.handleBusStudentsData)
      
      // 监听离校学生列表响应
      socketStore.on('departure-students-data', this.handleDepartureStudentsData)
      
      // 监听学生详情响应
      socketStore.on('student-detail-data', this.handleStudentDetailData)
      
      // 监听班级考勤详情响应
      socketStore.on('class-attendance-detail-data', this.handleClassAttendanceDetailData)
      
      // 监听校车列表响应
      socketStore.on('bus-list-data', this.handleBusListData)
      
      // 监听二维码扫描结果
      socketStore.on('qr-scan-result', this.handleQRScanResult)
      
      // 监听学生创建结果
      socketStore.on('student-created', this.handleStudentCreated)
      
      // 监听学生更新结果
      socketStore.on('student-updated', this.handleStudentUpdated)
      
      // 监听学生删除结果
      socketStore.on('student-deleted', this.handleStudentDeleted)
      
      // 监听批量状态更新结果
      socketStore.on('batch-status-update-result', this.handleBatchStatusUpdateResult)
      
      // 监听司机列表数据
      socketStore.on('drivers-data', this.handleDriversData)
      
      // 监听学生备注更新结果
      socketStore.on('student-notes-updated', this.handleStudentNotesUpdated)
    },
    
    // 处理WebSocket学生状态更新
    handleStudentStatusUpdate(data) {
      console.log('收到学生状态更新:', data)
      
      // 更新本地学生状态
      const studentIndex = this.students.findIndex(s => s.id === data.studentId)
      if (studentIndex !== -1) {
        this.students[studentIndex] = {
          ...this.students[studentIndex],
          ...data.student
        }
      }
      
      // 重新计算统计数据
      this.updateStatistics()
      this.checkOverdueStudents()
    },

    // 新增的WebSocket事件处理器
    handleStudentsAttendanceData(data) {
      console.log('收到学生考勤数据:', data)
      this.loading = false
      if (data.success) {
        this.students = data.students || []
        this.attendanceStats = data.stats || {}
        this.totalCount = data.total || 0
      } else {
        this.error = data.message || '获取学生考勤数据失败'
      }
    },

    handleClassesData(data) {
      console.log('收到班级列表数据:', data)
      this.loading = false
      if (data.success) {
        this.classes = data.classes || []
        this.classesList = data.classes || []
      } else {
        this.error = data.message || '获取班级列表失败'
      }
    },

    handleStudentsAdminData(data) {
      console.log('收到管理员学生列表数据:', data)
      this.loading = false
      if (data.success) {
        this.students = data.students || []
        this.pagination.total = data.total || 0
      } else {
        this.error = data.message || '获取学生列表失败'
      }
    },

    handleClassStudentsData(data) {
      console.log('收到班级学生列表数据:', data)
      this.loading = false
      if (data.success) {
        this.classStudents = data.students || []
        this.students = data.students || []
      } else {
        this.error = data.message || '获取班级学生列表失败'
      }
    },

    handleAttendanceSettingsData(data) {
      console.log('收到考勤设置数据:', data)
      this.loading = false
      if (data.success) {
        this.attendanceSettings = data.settings || {}
      } else {
        this.error = data.message || '获取考勤设置失败'
      }
    },

    handleBusStudentsData(data) {
      console.log('收到校车学生列表数据:', data)
      this.loading = false
      if (data.success) {
        this.busStudents = data.students || []
        this.students = data.students || []
      } else {
        this.error = data.message || '获取校车学生列表失败'
      }
    },

    handleDepartureStudentsData(data) {
      console.log('收到离校学生列表数据:', data)
      this.loading = false
      if (data.success) {
        this.departureStudents = data.data || []
        this.students = data.data || []
      } else {
        this.error = data.message || '获取离校学生列表失败'
      }
    },

    handleStudentDetailData(data) {
      console.log('收到学生详情数据:', data)
      this.loading = false
      if (data.success) {
        this.currentStudent = data.student || {}
      } else {
        this.error = data.message || '获取学生详情失败'
      }
    },

    handleClassAttendanceDetailData(data) {
      console.log('收到班级考勤详情数据:', data)
      this.loading = false
      if (data.success) {
        this.classAttendanceDetail = data.detail || {}
      } else {
        this.error = data.message || '获取班级考勤详情失败'
      }
    },

    handleBusListData(data) {
      console.log('收到校车列表数据:', data)
      this.loading = false
      if (data.success) {
        this.busList = data.buses || []
      } else {
        this.error = data.message || '获取校车列表失败'
      }
    },

    handleQRScanResult(data) {
      console.log('收到二维码扫描结果:', data)
      this.loading = false
      if (data.success) {
        // 根据扫描类型处理结果
        if (data.type === 'arrival') {
          this.handleArrivalUpdate(data)
        } else if (data.type === 'add_student') {
          // 添加学生到列表
          if (data.student) {
            const existingIndex = this.students.findIndex(s => s.id === data.student.id)
            if (existingIndex === -1) {
              this.students.push(data.student)
            } else {
              this.students[existingIndex] = data.student
            }
          }
        }
      } else {
        this.error = data.message || '二维码扫描失败'
      }
    },

    handleStudentCreated(data) {
      console.log('收到学生创建结果:', data)
      this.loading = false
      if (data.success) {
        // 添加新学生到列表
        if (data.student) {
          this.students.push(data.student)
          this.pagination.total += 1
        }
      } else {
        this.error = data.message || '创建学生失败'
      }
    },

    handleStudentUpdated(data) {
      console.log('收到学生更新结果:', data)
      this.loading = false
      if (data.success) {
        // 更新学生信息
        if (data.student) {
          const index = this.students.findIndex(s => s.id === data.student.id)
          if (index !== -1) {
            this.students[index] = { ...this.students[index], ...data.student }
          }
        }
      } else {
        this.error = data.message || '更新学生失败'
      }
    },

    handleStudentDeleted(data) {
      console.log('收到学生删除结果:', data)
      this.loading = false
      if (data.success) {
        // 从列表中移除学生
        if (data.studentId) {
          this.students = this.students.filter(s => s.id !== data.studentId)
          this.pagination.total -= 1
        }
      } else {
        this.error = data.message || '删除学生失败'
      }
    },
    
    // 处理批量状态更新结果
    handleBatchStatusUpdateResult(data) {
      console.log('收到批量状态更新结果:', data)
      this.loading = false
      if (data.success) {
        // 更新本地状态
        if (data.updates) {
          data.updates.forEach(update => {
            const studentIndex = this.students.findIndex(s => s.id === update.studentId)
            if (studentIndex !== -1) {
              this.students[studentIndex] = { ...this.students[studentIndex], ...update.statusData }
            }
          })
        }
        this.updateStatistics()
        this.checkOverdueStudents()
      } else {
        this.error = data.message || '批量更新学生状态失败'
      }
    },
    
    // 处理司机列表数据
    handleDriversData(data) {
      console.log('收到司机列表数据:', data)
      this.loading = false
      if (data.success) {
        this.drivers = data.drivers || []
      } else {
        this.error = data.message || '获取司机列表失败'
      }
    },
    
    // 处理学生备注更新结果
    handleStudentNotesUpdated(data) {
      console.log('收到学生备注更新结果:', data)
      if (data.success) {
        // 更新本地学生数据中的备注
        const studentIndex = this.students.findIndex(s => s.id === data.data.student.id)
        if (studentIndex !== -1) {
          this.students[studentIndex].notes = data.data.notes
        }
        
        // 显示成功提示
        window.showNotification?.('备注更新成功', 'success')
      } else {
        // 显示错误提示
        window.showNotification?.(data.message || '备注更新失败', 'error')
      }
    },
    
    // 处理WebSocket考勤记录更新
    handleAttendanceUpdate(data) {
      console.log('收到考勤数据更新:', data)
      
      // 更新统计数据
      if (data.stats) {
        this.statistics = {
          ...this.statistics,
          ...data.stats
        }
      }
      
      // 更新学生列表
      if (data.students) {
        this.students = data.students
      }
      
      // 根据更新类型处理
      if (data.update_type === 'arrival') {
        // 入园更新
        this.handleArrivalUpdate(data)
      } else if (data.update_type === 'departure') {
        // 离园更新
        this.handleDepartureUpdate(data)
      }
    },
    
    // 处理入园更新
    handleArrivalUpdate(data) {
      console.log('收到入园状态更新:', data)
      
      const studentIndex = this.students.findIndex(s => s.student_id === data.student_id || s.id === data.studentId)
      
      if (studentIndex !== -1) {
        // 更新学生入园状态
        this.students[studentIndex] = {
          ...this.students[studentIndex],
          arrival_status: data.status,
          arrival_time: data.timestamp || data.arrivalTime,
          notes: data.notes || this.students[studentIndex].notes
        }
        
        // 更新统计数据
        this.updateStatistics()
        
        // 检查异常学生
        this.checkOverdueStudents()
      }
    },
    
    // 处理离园更新
    handleDepartureUpdate(data) {
      console.log('收到离园状态更新:', data)
      
      const studentIndex = this.students.findIndex(s => s.student_id === data.student_id || s.id === data.studentId)
      
      if (studentIndex !== -1) {
        // 更新学生离园状态
        this.students[studentIndex] = {
          ...this.students[studentIndex],
          departure_status: data.status,
          departure_time: data.timestamp || data.departureTime,
          departure_method: data.departureMethod || this.students[studentIndex].departure_method,
          notes: data.notes || this.students[studentIndex].notes
        }
        
        // 更新统计数据
        this.updateStatistics()
      }
    },
    
    // 获取学生及考勤状态 - 使用WebSocket
    fetchStudentsWithAttendance(date = null) {
      const socketStore = useSocketStore()
      const targetDate = date || this.selectedDate
      socketStore.emit('get-students-attendance', { date: targetDate })
    },
    
    // 获取班级列表 - 使用WebSocket
    fetchClasses() {
      const socketStore = useSocketStore()
      socketStore.emit('get-classes')
    },
    
    // 更新学生状态 - 使用WebSocket
    updateStudentStatus(studentId, statusData) {
      const socketStore = useSocketStore()
      socketStore.emit('update-student-status', {
        studentId,
        statusData
      })
    },
    
    // 批量更新学生状态 - 使用WebSocket
    batchUpdateStudentStatus(updates) {
      const socketStore = useSocketStore()
      this.loading = true
      socketStore.emit('batch-update-student-status', { updates })
    },
    
    // 扫码更新学生入园状态 - 使用WebSocket
    scanQRCode(studentNumber) {
      const socketStore = useSocketStore()
      socketStore.emit('scan-qr-code', {
        student_number: studentNumber,
        date: this.selectedDate
      })
    },
    
    // 更新统计数据
    updateStatistics() {
      this.statistics.totalStudents = this.students.length
      this.statistics.arrivedStudents = this.students.filter(s => s.arrival_status === 'arrived').length
      this.statistics.departedStudents = this.students.filter(s => s.departure_status === 'departed').length
      this.statistics.overdueArrivals = this.getOverdueArrivals.length
    },
    
    // 检查超时学生
    checkOverdueStudents() {
      this.abnormalStudents = this.getOverdueArrivals.map(s => ({ ...s, abnormalType: 'overdue' }))
    },
    
    // 设置选中日期
    setSelectedDate(date) {
      this.selectedDate = date
      // 重新获取该日期的数据
      this.fetchStudentsWithAttendance(date)
    },
    
    // 开始实时更新
    startRealTimeUpdate() {
      if (this.updateTimer) {
        clearInterval(this.updateTimer)
      }
      
      this.updateTimer = setInterval(() => {
        this.fetchStudentsWithAttendance()
      }, this.updateInterval)
    },
    
    // 停止实时更新
    stopRealTimeUpdate() {
      if (this.updateTimer) {
        clearInterval(this.updateTimer)
        this.updateTimer = null
      }
    },
    
    // 设置更新间隔
    setUpdateInterval(interval) {
      this.updateInterval = interval
      if (this.updateTimer) {
        this.stopRealTimeUpdate()
        this.startRealTimeUpdate()
      }
    },
    
    // 清除错误
    clearError() {
      this.error = null
    },

    // 管理员功能 - 加载司机列表 - 使用WebSocket
    fetchDrivers() {
      const socketStore = useSocketStore()
      this.loading = true
      socketStore.emit('get-drivers')
    },

    // 管理员功能 - 加载学生列表（支持分页和搜索）- 使用WebSocket
    fetchStudentsForAdmin(params = {}) {
      const socketStore = useSocketStore()
      socketStore.emit('get-students-admin', params)
    },

    // 管理员功能 - 创建学生 - 使用WebSocket
    createStudent(studentData) {
      const socketStore = useSocketStore()
      socketStore.emit('create-student', studentData)
    },

    // 管理员功能 - 更新学生信息 - 使用WebSocket
    updateStudent(studentId, studentData) {
      const socketStore = useSocketStore()
      socketStore.emit('update-student', { studentId, studentData })
    },

    // 管理员功能 - 删除学生 - 使用WebSocket
    deleteStudent(studentId) {
      const socketStore = useSocketStore()
      socketStore.emit('delete-student', { studentId })
    },

    // 设置选中的班级
    setSelectedClass(classId) {
      this.selectedClass = classId
      
      // 如果选择了班级，加入班级WebSocket房间
      if (classId) {
        joinClassRoom(classId)
      }
    },

    // 设置搜索查询
    setSearchQuery(query) {
      this.searchQuery = query
    },

    // 设置分页
    setPagination(page, itemsPerPage) {
      this.pagination.page = page
      this.pagination.itemsPerPage = itemsPerPage
    },
    
    // 教师功能 - 获取班级学生列表 - 使用WebSocket
    fetchClassStudents(classId = null) {
      const socketStore = useSocketStore()
      socketStore.emit('get-class-students', { classId })
    },

    // 教师功能 - 扫码更新学生入园状态 - 使用WebSocket
    updateArrivalByQR(studentCode) {
      const socketStore = useSocketStore()
      socketStore.emit('qr-scan-arrival', { studentCode })
    },

    // 教师功能 - 手动更新学生入园状态 - 使用WebSocket
     updateArrivalStatus(studentId, status, notes = '') {
       const socketStore = useSocketStore()
       socketStore.emit('update-student-arrival', {
         studentId,
         status,
         notes,
         date: this.selectedDate
       })
     },

     // 教师功能 - 获取我的班级考勤信息 - 使用WebSocket
     fetchMyClassAttendance(params = {}) {
       const socketStore = useSocketStore()
       socketStore.emit('get-class-attendance', {
         ...params,
         date: params.date || this.selectedDate
       })
     },

     // 教师功能 - 更新学生入园状态 - 使用WebSocket
     updateStudentArrival(data) {
       const socketStore = useSocketStore()
       socketStore.emit('update-student-arrival', {
         ...data,
         date: this.selectedDate
       })
     },

     // 教师功能 - 获取班级离园考勤信息 - 使用WebSocket
     fetchMyClassDeparture(params = {}) {
       const socketStore = useSocketStore()
       socketStore.emit('get-class-departure', {
         ...params,
         date: params.date || this.selectedDate
       })
     },

     // 教师功能 - 更新学生离园状态 - 使用WebSocket
     updateStudentDeparture(data) {
       const socketStore = useSocketStore()
       socketStore.emit('update-student-departure', {
         ...data,
         date: this.selectedDate
       })
     },

     // 教师功能 - 获取考勤设置 - 使用WebSocket
     fetchAttendanceSettings() {
       const socketStore = useSocketStore()
       socketStore.emit('get-attendance-settings')
     },

     // 教师功能 - 加载学生考勤信息（通用）- 使用WebSocket
     loadStudentsWithAttendance(params = {}) {
       const socketStore = useSocketStore()
       socketStore.emit('get-students-attendance-list', params)
     },

     // 通用方法 - 更新学生考勤状态
     updateStudentAttendance(studentId, attendanceData) {
       const studentIndex = this.students.findIndex(s => s.id === studentId)
       if (studentIndex !== -1) {
         this.students[studentIndex] = {
           ...this.students[studentIndex],
           ...attendanceData
         }
       }
     },

     // 通用方法 - 更新学生离园状态（本地）
     updateStudentDeparture(studentId, departureData) {
       const studentIndex = this.students.findIndex(s => s.id === studentId)
       if (studentIndex !== -1) {
         this.students[studentIndex] = {
           ...this.students[studentIndex],
           ...departureData
         }
       }
     },

     // 司机功能 - 获取校车学生列表 - 使用WebSocket
     fetchBusStudents() {
       const socketStore = useSocketStore()
       socketStore.emit('get-bus-students')
     },

     // 司机功能 - 标记学生上车
     // 司机功能 - 标记学生到达 - 使用WebSocket
     markStudentArrived(studentId) {
       const socketStore = useSocketStore()
       socketStore.emit('mark-student-arrived', {
         studentId,
         status: 'arrived',
         arrivalTime: new Date().toISOString(),
         date: this.selectedDate
       })
     },

     // 司机功能 - 扫码添加学生 - 使用WebSocket
     addStudentByQR(studentCode) {
       const socketStore = useSocketStore()
       socketStore.emit('add-student-by-qr', { studentCode })
     },

     // 司机功能 - 获取离园学生列表 - 使用WebSocket
     fetchDepartureStudents() {
       const socketStore = useSocketStore()
       socketStore.emit('get-departure-students', {
         date: this.selectedDate
       })
     },

     // 司机功能 - 标记学生离园 - 使用WebSocket
     markStudentDeparted(studentId) {
       const socketStore = useSocketStore()
       socketStore.emit('mark-student-departed', {
         studentId,
         status: 'departed',
         date: this.selectedDate
       })
     },

     // 司机功能 - 更新学生离园状态 - 使用WebSocket
     updateDriverDepartureStatus(studentId, status, notes = '') {
       const socketStore = useSocketStore()
       socketStore.emit('update-driver-departure-status', {
         studentId,
         status,
         notes,
         date: this.selectedDate
       })
     },

     // 获取考勤设置（用于司机离园管理）- 使用WebSocket
     fetchAttendanceSettingsForDriver() {
       const socketStore = useSocketStore()
       socketStore.emit('get-driver-attendance-settings')
     },

     // 获取单个学生详细信息 - 使用WebSocket
     fetchStudentDetail(studentId) {
       const socketStore = useSocketStore()
       socketStore.emit('get-student-detail', { studentId })
     },

     // 获取班级考勤详情（用于管理员仪表盘）- 使用HTTP API
     async fetchClassAttendanceDetail(classId, date) {
       try {
         const response = await api.get(`/attendance/class-attendance/${classId}`, {
           params: { date }
         })
         
         if (response.data.success) {
           // 更新store中的班级考勤详情数据
           this.classAttendanceDetail = response.data.data || {}
           return response.data
         } else {
           throw new Error(response.data.message || '获取班级考勤详情失败')
         }
       } catch (error) {
         console.error('获取班级考勤详情失败:', error)
         this.error = error.message || '获取班级考勤详情失败'
         throw error
       }
     },

     // 获取校车列表（教师离园管理用）- 使用WebSocket
     fetchBusList() {
       const socketStore = useSocketStore()
       socketStore.emit('get-bus-list')
     },

     // 标记学生入园状态（教师入园管理用）- 使用WebSocket
     markStudentArrival(data) {
       const socketStore = useSocketStore()
       socketStore.emit('mark-student-arrival', data)
      },
      
     // 更新学生备注（独立功能，不与状态绑定）- 使用WebSocket
     updateStudentNotes(studentId, notes) {
       const authStore = useAuthStore()
       const socketStore = useSocketStore()
       socketStore.emit('update-student-notes', {
         studentId,
         notes,
         teacherId: authStore.user?.id,
         userRole: authStore.user?.role
       })
     },

     // 标记学生离园状态（教师离园管理用）- 使用WebSocket
     markStudentDeparture(data) {
       const socketStore = useSocketStore()
       socketStore.emit('mark-student-departure', data)
     },

     // 确认学生实际离校（教师离园管理用）- 使用WebSocket
     confirmStudentDeparture(studentId) {
       const socketStore = useSocketStore()
       socketStore.emit('confirm-student-departure', { studentId })
     },

     // 新状态系统API方法
     // 设置学生离校方式
     async setDepartureMethod(studentId, method) {
       try {
         const response = await api.post('/attendance/set-departure-method', {
           student_id: studentId,
           departure_method: method
         })
         if (response.data.success) {
           // 更新本地状态
           const studentIndex = this.students.findIndex(s => s.id === studentId)
           if (studentIndex !== -1) {
             this.students[studentIndex].departure_method = method
           }
         }
         return response.data
       } catch (error) {
         console.error('设置离校方式失败:', error)
         throw error
       }
     },

     // 学生离班（普通教师）
     async leaveClass(studentId) {
       try {
         const response = await api.post('/attendance/leave-class', {
           student_id: studentId
         })
         if (response.data.success) {
           // 更新本地状态
           const studentIndex = this.students.findIndex(s => s.id === studentId)
           if (studentIndex !== -1) {
             const method = this.students[studentIndex].departure_method
             if (['bus', 'parent_pickup'].includes(method)) {
               this.students[studentIndex].attendance_status = 'left_school'
             } else {
               this.students[studentIndex].attendance_status = 'left_class'
             }
           }
         }
         return response.data
       } catch (error) {
         console.error('离班失败:', error)
         throw error
       }
     },

     // 学生进班（课后教师）
     async enterClass(studentId) {
       try {
         const response = await api.post('/attendance/enter-class', {
           student_id: studentId
         })
         if (response.data.success) {
           // 更新本地状态
           const studentIndex = this.students.findIndex(s => s.id === studentId)
           if (studentIndex !== -1) {
             this.students[studentIndex].attendance_status = 'entered_class'
           }
         }
         return response.data
       } catch (error) {
         console.error('进班失败:', error)
         throw error
       }
     },

     // 课后离班（课后教师）
     async leaveAfterSchoolClass(studentId) {
       try {
         const response = await api.post('/attendance/leave-after-school-class', {
           student_id: studentId
         })
         if (response.data.success) {
           // 更新本地状态
           const studentIndex = this.students.findIndex(s => s.id === studentId)
           if (studentIndex !== -1) {
             this.students[studentIndex].attendance_status = 'left_school'
           }
         }
         return response.data
       } catch (error) {
         console.error('课后离班失败:', error)
         throw error
       }
     },

     // 学生请假
     async requestLeave(studentId) {
       try {
         const response = await api.post('/attendance/request-leave', {
           student_id: studentId
         })
         if (response.data.success) {
           // 更新本地状态
           const studentIndex = this.students.findIndex(s => s.id === studentId)
           if (studentIndex !== -1) {
             this.students[studentIndex].attendance_status = 'on_leave'
           }
         }
         return response.data
       } catch (error) {
         console.error('请假失败:', error)
         throw error
       }
     },

    // 重置store状态
    // 处理定期状态更新
    handlePeriodicUpdate(studentsData) {
      try {
        if (!studentsData || !Array.isArray(studentsData)) {
          return
        }
        
        // 更新学生状态数据
        studentsData.forEach(updatedStudent => {
          const existingIndex = this.students.findIndex(s => s.id === updatedStudent.student_id)
          if (existingIndex !== -1) {
            // 更新现有学生的状态
            this.students[existingIndex] = {
              ...this.students[existingIndex],
              arrival_status: updatedStudent.arrival_status,
              departure_status: updatedStudent.departure_status,
              notes: updatedStudent.notes,
              updated_at: updatedStudent.updated_at
            }
          }
        })
        
        // 重新计算统计数据
        this.updateStatistics()
        
        console.log('📊 学生状态已通过定期更新同步')
      } catch (error) {
        console.error('处理定期状态更新失败:', error)
      }
    },

    resetStore() {
      this.students = []
      this.classesList = []
      this.selectedDate = new Date().toISOString().split('T')[0]
      this.loading = false
      this.error = null
      this.abnormalStudents = []
      this.statistics = {
        totalStudents: 0,
        arrivedStudents: 0,
        departedStudents: 0,
        overdueArrivals: 0
      }
      this.drivers = []
      this.selectedClass = null
      this.pagination = {
        page: 1,
        itemsPerPage: 10,
        total: 0
      }
      this.searchQuery = ''
      this.stopRealTimeUpdate()
    }
  }
})